package com.example.demo.controller;

import com.example.demo.DTO.SubmitPaperDto;
import com.example.demo.entity.ExamHistory;
import com.example.demo.entity.WrongQuestion;
import com.example.demo.jwt.Jwt;
import com.example.demo.response.Response;
import com.example.demo.service.ExamHistoryService;
import com.example.demo.service.WrongQuestionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;


@Api(tags="回答控制器")
@RequestMapping(path = "/answer")
@RestController
public class AnswerController {

  @Autowired
  WrongQuestionService wrongQuestionService;
  @Autowired
  ExamHistoryService examHistoryService;

  @ApiOperation("提交试卷")
  @RequestMapping(path = "/submit",method = RequestMethod.POST)
  @Transactional(rollbackFor = Exception.class)
  public Response submit (@RequestHeader("token") String token, @RequestBody SubmitPaperDto submitPaperDto){
    Response res = new Response(500,"","没有token");
    if(token == ""){
      return res;
    }
    String userId = Jwt.decode(token);
    ExamHistory examHistory = new ExamHistory();
    examHistory.setPaperId(submitPaperDto.getPaperId());
    examHistory.setUserId(userId);
    String now = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    examHistory.setExamDate(now);
    try{
      examHistoryService.addExamHistory(examHistory);
    } catch (Exception e){
      System.out.println(e);
      res.setMessage(e.toString());
      return res;
    }
    for(int i=0;i<submitPaperDto.getWrongList().size();i++){
      WrongQuestion wrongQuestion = new WrongQuestion();
      wrongQuestion.setUserId(userId);
      wrongQuestion.setQuestionId(submitPaperDto.getWrongList().get(i));
      try{
        wrongQuestionService.addWrongQuestion(wrongQuestion);
      }catch (Exception e){
        System.out.println(e);
        res.setMessage(e.toString());
        return res;
      }
    }
    res.setCode(200);
    res.setData("ok");
    res.setMessage("成功");
    return res;
  }
}
